package com.ustcinfo.study.hive.r2.yangxinxin;



import java.sql.*;

public class HiveConnectionyangxinxin {
    //hive 链接地址
    private static  String url="jdbc:hive2://node1:10000/default";
    //hive 用户名
    private  static  String userName="hive";
    //hive 密码
    private static  String passwd="hive";
     //hive 驱动
    private static String driver="org.apache.hive.jdbc.HiveDriver";

    private  static Connection connection=null;
    private  static Statement statement=null;
    private  static ResultSet resultSet=null;

    //查询tables sql
    private  static String showTableSql="show tables";

    //创建内部表dnsSample sql
    private  static  String createSql="create table dnsSample(ip string,domain_name string,access_time string,target_ip string,status string)row format delimited fields terminated by '#' ";
    //加载数据到dnsSample sql
    private  static String localDataSql="load data local inpath '/root/hadoop/dnsSampleData' into table dnsSample";

    //统计出表中域名个数
    private  static  String countSql="select count(distinct domain_name) from dnsSample  ";



    public  static  void main (String[] args) throws SQLException{
        //加载hive驱动
        try {
            Class.forName(driver);
        }catch(ClassNotFoundException e){
            System.out.println("驱动加载失败");
            e.printStackTrace();
        }


        try{
            //连接hive
            connection= DriverManager.getConnection(url,userName,passwd);
            if (connection != null){
                System.out.println("hive连接成功");
            }else{
                System.out.println("hive连接失败");
            }

            statement=connection.createStatement();

            //获取数据库中所有的表
            resultSet=statement.executeQuery(showTableSql);
            while (resultSet.next()){
                System.out.println(resultSet.getString(1));
            }

            statement.execute(createSql);
            statement.execute(localDataSql);
            resultSet=statement.executeQuery(countSql);
            while(resultSet.next()){
                System.out.println(resultSet.getString(1)+"\t"+resultSet.getInt(2));
            }
        }catch (SQLException e){
            e.printStackTrace();
            System.exit(1);
        }finally {

            if (statement != null){
                statement.close();
            }
            if (connection != null){
                connection.close();
            }
            if (resultSet != null){
                resultSet.close();
            }
        }
    }
}
